package com.cook.controller;

import com.cook.service.EmailLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@Slf4j
public class EmailLoginController {

    private final EmailLoginService emailLoginService;
    private final RedisTemplate<String, String> redisTemplate;

    @PostMapping("/email/login")
    public ResponseEntity<String> loginByEmail(@RequestParam String email, @RequestParam String code) {
        // 先查询Redis中存储的验证码
        String storedCode = (String)this.redisTemplate.opsForValue().get("email:code:" + email);

        if (storedCode == null) {
            return ResponseEntity.status(401).body("验证码已过期");
        }

        if (code.equals(storedCode)) {
            // 登录成功，删除已使用的验证码
            this.redisTemplate.delete("email:code:" + email);
            return ResponseEntity.ok("登录成功");
        } else {
            return ResponseEntity.status(401).body("验证码错误");
        }
    }

    // 单独的发送验证码接口
    @PostMapping("/email/sendCode")
    public ResponseEntity<String> sendVerificationCode(@RequestParam String email) {
        this.emailLoginService.sendVerificationCode(email);
        return ResponseEntity.ok("验证码发送成功");
    }
}
